﻿/*
 * 由SharpDevelop创建。
 * 用户： liang
 * 日期: 2015/12/26 星期六
 * 时间: 19:35
 *
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO.Ports;
using System.Text;
using VCOM.Properties;
using System.Data;



namespace VCOM
{

	/// <summary>
	/// Description of MainForm.
	/// </summary>

	public partial class MainForm : Form
	{
		private SerialPort sp = new SerialPort();
		public Timer Timer1 = new Timer();
		//private int rxCount = 0;
		private int[] rxBuffer = new int[1024];
		public delegate void UpdateTextEventHandler(string revText);
		public UpdateTextEventHandler updateText;
		public OpenFileDialog ofd;
		public string binPath;
		public byte[] binBuffer;
		public UInt32 binSize;
		public UInt32 gFlgRecvOK = 0;
		public UInt16 sMsgLen = 0;
		public bool sFlgSendOver = false;

		public byte[] sendBuffer;

		public MainForm()
		{

			InitializeComponent();
			this.sp.DataReceived += new SerialDataReceivedEventHandler(this.serialPort_DataReceived);
			cbxParity.DropDownStyle = ComboBoxStyle.DropDownList;
			cbxDataBits.DropDownStyle = ComboBoxStyle.DropDownList;
			cbxBaudRate.DropDownStyle = ComboBoxStyle.DropDownList;
			cbxComPort.DropDownStyle = ComboBoxStyle.DropDownList;
			cbxStopBits.DropDownStyle = ComboBoxStyle.DropDownList;


		}
		void MainFormLoad(object sender, EventArgs e)
		{
			foreach(string str in System.IO.Ports.SerialPort.GetPortNames())
			{
				cbxComPort.Items.Add(str);
			}

			cbxBaudRate.Items.Add("自定义");
			cbxBaudRate.Items.Add("115200");
			cbxBaudRate.Items.Add("9600");
			cbxBaudRate.Items.Add("4800");
			cbxStopBits.Items.Add("1");
            cbxStopBits.Items.Add("1.5");
            cbxStopBits.Items.Add("2");
            cbxDataBits.Items.Add("8");
            cbxDataBits.Items.Add("7");
            cbxDataBits.Items.Add("6");
            cbxDataBits.Items.Add("5");
            cbxParity.Items.Add("无");
            cbxParity.Items.Add("奇检验");
            cbxParity.Items.Add("偶检验");

            sp.WriteTimeout = 3000;
            sp.ReadTimeout = 3000;


            initAllSerialPortSettings();
			if(cbxComPort.Items.Count == 0)
			{
				MessageBox.Show("没有连接串口");
			}
			else
			{
				initOpenSerialPort();
			}

			updateText = new UpdateTextEventHandler(UpdateTextBox);
			rdBtn_sp.Checked = true;
			rdBtn_STM32.Checked = false;
			rdBtn_ST87.Checked = false;
			ckbx_SendHex.Checked = false;
			ckbx_XinHang.Checked = true;

			progressBar1.Visible = false;

		}

		public void openSerialPort()
        {
            try
            {
                sp.Open();
            }
            catch (Exception)
            {
                MessageBox.Show("打开串口失败");
            }
            if(sp.IsOpen)
            {
            	btnOpenCom.Text = "关闭串口";
            }
        }

		private void closeSerialPort()
        {
            try
            {
                sp.Close();
            }
            catch
            {
            	MessageBox.Show("关闭串口失败");
            }
            if(!sp.IsOpen)
            {
            	btnOpenCom.Text = "打开串口";
            }
        }

		private void initOpenSerialPort()
        {
            if (!sp.IsOpen)
            {
                if (cbxComPort.Items.Count == 0)
                {
                    MessageBox.Show("没有搜索到串口！", "错误提示");
                }
                else
                {
                    SetPortProperty();
                    openSerialPort();
                }
            }
            else
            {
                closeSerialPort();
            }
        }

		private void initAllSerialPortSettings()
        {
            if (cbxComPort.Items.Count != 0)
            {
            	Settings.Default.PortName = cbxComPort.Items[0].ToString();
            	cbxComPort.Text = Settings.Default.PortName;

            	if (cbxBaudRate.Items.Contains(Settings.Default.BaudRate))
	            {
	                cbxBaudRate.Text = Settings.Default.BaudRate;
	            }
	            else
	            {
	                cbxBaudRate.Text = "115200";
	            }
	            cbxStopBits.Text = Settings.Default.StopBits;
	            cbxDataBits.Text = Settings.Default.DataBits;
	            cbxParity.Text = Settings.Default.Parity;
            }
            else
            {
               	cbxBaudRate.Text = "115200";
               	cbxStopBits.Text = "1";
	            cbxDataBits.Text = "8";
	            cbxParity.Text = "无";
            }

            tbxSendData_1.Text = Settings.Default.TxbSendData_1;
			tbxSendData_2.Text = Settings.Default.TxbSendData_2;
			tbxSendData_3.Text = Settings.Default.TxbSendData_3;
			tbxSendData_4.Text = Settings.Default.TxbSendData_4;
			tbxSendData_5.Text = Settings.Default.TxbSendData_5;
			tbxSendData_6.Text = Settings.Default.TxbSendData_6;
			tbxSendData_7.Text = Settings.Default.TxbSendData_7;
			tbxSendData_8.Text = Settings.Default.TxbSendData_8;
			tbxSendData_9.Text = Settings.Default.TxbSendData_9;
			tbxSendData_10.Text = Settings.Default.TxbSendData_10;

		}

		private void SetPortProperty()
        {
            sp.Encoding = Encoding.GetEncoding("GB18030");
            if (cbxComPort.Text != "")
            {
                sp.PortName = cbxComPort.Text.Trim();
            }
            else
            {
                sp.PortName = "XXXX";
            }
            if (cbxBaudRate.Text.Trim() != "自定义")
            {
                try
                {
                   	sp.BaudRate = Convert.ToInt32(cbxBaudRate.Text.Trim());
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.ToString(), "异常");
                }
            }

            if(cbxDataBits.Text != "")
            {
            	sp.DataBits = Convert.ToInt16(cbxDataBits.Text.Trim());
            }
            else
            {
            	cbxDataBits.Text = "8";
            	sp.DataBits = Convert.ToInt16(cbxDataBits.Text.Trim());
            }


            if (cbxStopBits.Text == "1.5")
            {
                sp.StopBits = StopBits.OnePointFive;
            }
            else if (cbxStopBits.Text == "1")
            {
                sp.StopBits = StopBits.One;
            }
            else if (cbxStopBits.Text == "2")
            {
                sp.StopBits = StopBits.Two;
            }
            else
            {
                sp.StopBits = StopBits.One;
                cbxStopBits.Text = "1";
            }

            if (cbxParity.Text == "无")
            {
                sp.Parity = Parity.None;
            }
            else if (cbxParity.Text == "奇校验")
            {
                sp.Parity = Parity.Odd;
            }
            else if (cbxParity.Text == "偶校验")
            {
                sp.Parity = Parity.Even;
            }
            else
            {
                sp.Parity = Parity.None;
                cbxParity.Text = "无";
            }

        }

		private void saveAllSerialPortSettings()
        {
            Settings.Default.PortName = cbxComPort.Text;
            Settings.Default.BaudRate = cbxBaudRate.Text;
            Settings.Default.StopBits = cbxStopBits.Text;
            Settings.Default.DataBits = cbxDataBits.Text;
            Settings.Default.Parity = cbxParity.Text;
            Settings.Default.TxbSendData_1 = tbxSendData_1.Text;
            Settings.Default.TxbSendData_2 = tbxSendData_2.Text;
            Settings.Default.TxbSendData_3 = tbxSendData_3.Text;
            Settings.Default.TxbSendData_4 = tbxSendData_4.Text;
            Settings.Default.TxbSendData_5 = tbxSendData_5.Text;
            Settings.Default.TxbSendData_6 = tbxSendData_6.Text;
            Settings.Default.TxbSendData_7 = tbxSendData_7.Text;
            Settings.Default.TxbSendData_8 = tbxSendData_8.Text;
            Settings.Default.TxbSendData_9 = tbxSendData_9.Text;
            Settings.Default.TxbSendData_10 = tbxSendData_10.Text;

            Settings.Default.Save();
        }

		void MainFormFormClosing(object sender, FormClosingEventArgs e)
		{
			saveAllSerialPortSettings();
		}

		void CbxComPortSelectedIndexChanged(object sender, EventArgs e)
		{
			if (sp.IsOpen)
            {
                closeSerialPort();
            }
			sp.PortName = cbxComPort.Text.Trim();
		}

		void CbxComPortClick(object sender, EventArgs e)
		{
			closeSerialPort();
			cbxComPort.Items.Clear();
			foreach(string str in System.IO.Ports.SerialPort.GetPortNames())
			{
				cbxComPort.Items.Add(str);
			}
		}

		void CbxBaudRateSelectedIndexChanged(object sender, EventArgs e)
		{
			if (sp.IsOpen)
            {
                closeSerialPort();
            }
            if (cbxBaudRate.Text.Trim() == "自定义")
            {
                cbxBaudRate.DropDownStyle = ComboBoxStyle.DropDown;
                sp.BaudRate = 0x2580;
            }
            else
            {
                cbxBaudRate.DropDownStyle = ComboBoxStyle.DropDownList;
                sp.BaudRate = Convert.ToInt32(cbxBaudRate.Text.Trim());
            }
		}
		void CbxStopBitsSelectedIndexChanged(object sender, EventArgs e)
		{
			if (sp.IsOpen)
            {
                closeSerialPort();
	        }

			if (cbxStopBits.Text == "1.5")
            {
                sp.StopBits = StopBits.OnePointFive;
            }
            else if (cbxStopBits.Text == "1")
            {
                sp.StopBits = StopBits.One;
            }
            else if (cbxStopBits.Text == "2")
            {
                sp.StopBits = StopBits.Two;
            }
            else
            {
                sp.StopBits = StopBits.One;
                cbxStopBits.Text = "1";
            }
		}
		void CbxDataBitsSelectedIndexChanged(object sender, EventArgs e)
		{
			if (sp.IsOpen)
            {
                closeSerialPort();
            }
			sp.DataBits = Convert.ToInt16(cbxDataBits.Text.Trim());
		}
		void CbxParitySelectedIndexChanged(object sender, EventArgs e)
		{
			if (sp.IsOpen)
            {
				closeSerialPort();
            }

			if (cbxParity.Text == "无")
            {
                sp.Parity = Parity.None;
            }
            else if (cbxParity.Text == "奇校验")
            {
                sp.Parity = Parity.Odd;
            }
            else if (cbxParity.Text == "偶校验")
            {
                sp.Parity = Parity.Even;
            }
            else
            {
                sp.Parity = Parity.None;
                cbxParity.Text = "无";
            }
		}
		void BtnOpenComClick(object sender, EventArgs e)
		{
			if(btnOpenCom.Text == "打开串口")
			{
				openSerialPort();
			}
			else
			{
				closeSerialPort();
			}
		}

		public void UpdateTextBox(string revText)
        {
			if(rdBtn_sp.Checked == true)
			{
				revText = Utils.HexToStr(revText);
				tbxRecvData.AppendText(revText);
			}
			if(rdBtn_updata.Checked == true)
			{
//				tbxRecvData.AppendText("recv data: " + revText);	//test print
				int index = revText.IndexOf("5F5F");//查找帧头

				if(index < 0)
					return;

				/* 获取数据长度 */
				string strNum = revText.Substring(index+4,4);
				char[] Num = strNum.ToCharArray();
				byte[] Nump = new byte[Num.Length];
				byte[] Numdes = new byte[Num.Length];

				for(int i=0;i<Num.Length;i++)
				{
					Nump[i] = Convert.ToByte(Num[i]);
				}
				Ascii2Byte(Numdes,Nump,(UInt16)((Num.Length)));

				int DataLen = Numdes[0]<<0|Numdes[1] << 8;//获取帧长度
				/*********************/

				string str = revText.Substring(index,(DataLen+6)*2);//截取帧数据

				if(sFlgSendOver)
					return;
				char[] ack = str.ToCharArray();
				byte[] p = new byte[ack.Length];
				byte[] des = new byte[ack.Length];

				for(int i=0;i<ack.Length;i++)
				{
					p[i] = Convert.ToByte(ack[i]);
				}
				Ascii2Byte(des,p,(UInt16)(ack.Length-4));

				if((des[0] == 0x5F)&&(des[1] == 0x5F))
				{
					timer1.Stop();
					UInt16 MsgLen = (UInt16)(des[2]|des[3]<<8);
					UInt16 RecvCheckSum = (UInt16)(des[8]|des[9]<<8);
					UInt16 CalCheckSum = CheckSum16(des,4,4);
			        if(RecvCheckSum != CalCheckSum)
			            return;
			        UInt16 FunID = (UInt16)(des[4]|des[5]<<8);
			        UInt16 FrameNum = (UInt16)(des[6]|des[7]<<8);
//			        tbxRecvData.AppendText(" FunID :"+FunID+" ");	//test print
			        if(FrameNum > progressBar1.Maximum)
			        	MessageBox.Show("请求帧号超出最大值");
			        progressBar1.Value = FrameNum;
			        gFlgRecvOK = 1;
			        switch(FunID)
			        {
			        	case 2:
			        		byte[] tmpbyte = new byte[1200];
					        sendBuffer = new byte[1200 * 2];
//					        tbxRecvData.AppendText("发送第"+FrameNum+"帧\r\n");	//test print
					        UInt16 sDataLen = 0;
					        UInt16 sFunID = 2;
					        if((binSize-512*(FrameNum-1))/512 != 0)
			        		{
			        			sDataLen = 512;
			        			sMsgLen = (UInt16)(sDataLen+6);
			        			tmpbyte[0] = 0x5F;
					            tmpbyte[1] = 0x5F;
					            tmpbyte[2] = (byte)(sMsgLen&0xFF);
					            tmpbyte[3] = (byte)((sMsgLen>>8)&0xFF);
					            tmpbyte[4] = (byte)(sFunID&0xFF);
					            tmpbyte[5] = (byte)((sFunID>>8)&0xFF);
					            tmpbyte[6] = (byte)(FrameNum&0xFF);
					            tmpbyte[7] = (byte)((FrameNum>>8)&0xFF);
					            for(int i=0;i<sDataLen;i++)
					            {
					            	tmpbyte[8+i] = binBuffer[i+(FrameNum-1)*512];
					            }
					            UInt16 MsgCheckSum16 = CheckSum16(tmpbyte,4,(UInt16)(sDataLen+4));
					            tmpbyte[512+8+0] = (byte)(MsgCheckSum16&0xFF);
					            tmpbyte[512+8+1] = (byte)((MsgCheckSum16>>8)&0xFF);
					            tmpbyte[512+8+2] = 0x55;
					            tmpbyte[512+8+3] = 0xAA;
			        		}
			        		else
			        		{
			        			sDataLen = (UInt16)(binSize%512);
			        			sMsgLen = (UInt16)(sDataLen+6);
			        			tmpbyte[0] = 0x5F;
					            tmpbyte[1] = 0x5F;
					            tmpbyte[2] = (byte)(sMsgLen&0xFF);
					            tmpbyte[3] = (byte)((sMsgLen>>8)&0xFF);
					            tmpbyte[4] = (byte)(sFunID&0xFF);
					            tmpbyte[5] = (byte)((sFunID>>8)&0xFF);
					            tmpbyte[6] = (byte)(FrameNum&0xFF);
					            tmpbyte[7] = (byte)((FrameNum>>8)&0xFF);
					            for(int i=0;i<sDataLen;i++)
					            {
					            	tmpbyte[8+i] = binBuffer[i+(FrameNum-1)*512];
					            }
					            UInt16 MsgCheckSum16 = CheckSum16(tmpbyte,4,(UInt16)(sDataLen+4));
					            tmpbyte[sDataLen+8+0] = (byte)(MsgCheckSum16&0xFF);
					            tmpbyte[sDataLen+8+1] = (byte)((MsgCheckSum16>>8)&0xFF);
					            tmpbyte[sDataLen+8+2] = 0x55;
					            tmpbyte[sDataLen+8+3] = 0xAA;
			        		}
			        		Byte2Ascii(sendBuffer,tmpbyte,(UInt16)(sMsgLen+6));

				            if(sp.IsOpen)
				            {
				            	if(rdBtn_STM32.Checked == true)
				            	{
					            	sendSerailPortData("IIAP_STM32");
					            	sp.Write(sendBuffer, 0, (int)((6+sMsgLen)*2));
					            	sendSerailPortData("\r\n");
				            	}
				            	else
				            	{
				            		sendSerailPortData("IIAP_ST87");
					            	sp.Write(sendBuffer, 0, (int)((6+sMsgLen)*2));
					            	sendSerailPortData("\r\n");
				            	}
				            }
				            gFlgRecvOK = 0;
				            timer1.Start();
			        		break;
			        	case 3:
			        		// tbxRecvData.AppendText("设备写入flash失败\r\n");
			        		MessageBox.Show("设备写入flash失败");
			        		progressBar1.Visible = false;
			        		break;
			        	case 4:
			        		// tbxRecvData.AppendText("设备第"+FrameNum+"帧校验失败\r\n");
			        		MessageBox.Show("设备第"+FrameNum+"帧校验失败");
			        		break;
			        	case 5:
			        		sFlgSendOver = true;
			        		progressBar1.Value = progressBar1.Maximum;
			        		// tbxRecvData.AppendText("升级成功\r\n");
			        		MessageBox.Show("升级成功");

			        		progressBar1.Value = 0;
			        		progressBar1.Visible = false;
			        		break;
			        	case 6:
			        		// tbxRecvData.AppendText("设备flash擦除失败\r\n");
			        		MessageBox.Show("设备flash擦除失败");
			        		progressBar1.Visible = false;
			        		break;
			        	case 7:
			        		// tbxRecvData.AppendText("设备接收数据大于升级文件\r\n");
			        		MessageBox.Show("设备接收数据大于升级文件");
			        		progressBar1.Visible = false;
			        		break;
			        	case 8:
			        		// tbxRecvData.AppendText("设备接收数据超时\r\n");
			        		MessageBox.Show("设备 接收数据超时");
			        		progressBar1.Visible = false;
			        		break;
			        	default:
			        		break;
			        }
				}
			}

        }

		void Timer1Tick(object sender, EventArgs e)
		{

			if(sp.IsOpen)
            {
				timer1.Stop();
				MessageBox.Show("串口 等待数据超时");
				rdBtn_sp.Checked = true;

				sFlgSendOver = true;
				tbxRecvData.Clear();
				progressBar1.Visible = false;
            }

		}

		void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
		{
			System.Threading.Thread.Sleep(10);
			if (sp.IsOpen)
            {
                try
                {
					int count = 0;
                    string s = string.Empty;
                    byte[] buffer = new byte[sp.BytesToRead];
                    count = sp.Read(buffer, 0, buffer.Length);

                    StringBuilder builder = new StringBuilder();
                    for (int i = 0; i < count; i++)
                    {
                        builder.Append(Convert.ToString(buffer[i], 0x10).ToUpper().PadLeft(2, '0'));
                    }
                    s = builder.ToString();

                    Invoke(updateText, new string[] { s });
                }
                catch
                {

                }

            }
		}


		void sendMultiSerialPortData(string data)
		{
			if(ckbx_XinHang.Checked == true)
			{
				if(ckbx_SendHex.Checked == true)
				{
					sendSerailPortDataByHex(data + " 0D 0A");
				}
				else
				{
					sendSerailPortData(data + "\r\n");
				}
			}
			else
			{
				if(ckbx_SendHex.Checked == true)
				{
					sendSerailPortDataByHex(data);
				}
				else
				{
					sendSerailPortData(data);
				}
			}

		}

		private void sendSerailPortData(string data)
        {
            if (sp.IsOpen)
            {
                try
                {
                    byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(data);
                    int length = bytes.Length;
                    sp.Write(bytes, 0, length);
                }
                catch (Exception)
                {
                    MessageBox.Show("发送数据时发生错误, 串口将被关闭！", "错误提示");
                    closeSerialPort();
                }
            }
            else
            {
                MessageBox.Show("串口未打开，请先打开串口！", "错误提示");
            }
        }

		private void sendSerailPortDataByHex(string str)
        {
            string[] strArray = str.Split(new char[] { ' ' });
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < strArray.Length; i++)
            {
                builder.Append(strArray[i]);
            }
            str = builder.ToString();
            if ((str.Length % 2) != 0)
            {
                str = str.Insert(str.Length - 1, "0");
            }
            byte[] buffer = new byte[str.Length / 2];
            for (int j = 0; j < (str.Length / 2); j++)
            {
                try
                {
                    buffer[j] = Convert.ToByte(str.Substring(j * 2, 2), 0x10);
                }
                catch
                {
                    MessageBox.Show("包含非16进制字符，发送失败！", "提示");
                    return;
                }
            }
            if (this.sp.IsOpen)
            {
                try
                {
                    this.sp.Write(buffer, 0, buffer.Length);
                }
                catch (Exception)
                {
                    MessageBox.Show("发送数据时发生错误, 串口将被关闭！", "错误提示");
                    closeSerialPort();
                }
            }
            else
            {
                MessageBox.Show("串口未打开，请先打开串口！", "错误提示");
            }
        }
		void BtnOpenSendFileClick(object sender, EventArgs e)
		{
			//点击弹出对话框
            ofd = new OpenFileDialog();
            //设置对话框的标题
            ofd.Title = "请选择要打开的文本文件哟亲 O(∩_∩)O~";
            //设置对话框可以多选
            ofd.Multiselect = true;
            //设置对话框的初始目录
            ofd.InitialDirectory = @"C:\Users\SpringRain\Desktop";
            //设置对话框的文件类型
            ofd.Filter = "二进制文件|*.bin|所有文件|*.*";
            //展示对话框
            ofd.ShowDialog();

            //获得在打开对话框中选中文件的路径
            binPath = ofd.FileName;
            if (binPath == "")
            {
                return;
            }
            tbxSendFile.Text = binPath;
            using (FileStream fsRead = new FileStream(binPath, FileMode.OpenOrCreate, FileAccess.Read))
            {
                binBuffer = new byte[1024 * 1024 * 5];
                //实际读取到的字节数
                binSize = (UInt32)fsRead.Read(binBuffer, 0, binBuffer.Length);

                //textBox1.Text = Encoding.Default.GetString(binBuffer, 0, binSize);

            }
		}

		UInt16 CheckSum16(byte[] buf,UInt32 index,UInt32 len)
		{
			UInt32    i=0;
			UInt32 Sum=0;
		    UInt16 CheckSum=0;

		    for (i=index;i<(len+index);i++)
			{
				Sum+=buf[i];
			}
			CheckSum = (UInt16)((Sum >>16) + (Sum & 0xffff));
			return CheckSum;
		}
		void BtnSendFileClick(object sender, EventArgs e)
		{
			tbxRecvData.Clear();
			sFlgSendOver = false;
			UInt16 binCheckSum16 = CheckSum16(binBuffer,0,binSize);
			tbxRecvData.AppendText("升级文件字节数："+binSize.ToString()+"\r\n");
			tbxRecvData.AppendText("升级文件校验和："+binCheckSum16.ToString()+"\r\n");
			if(binSize == 0)
			{
				//tbxRecvData.AppendText("\r\n请选择升级文件\r\n");
				MessageBox.Show("请选择升级文件");
				return;
			}
			if(rdBtn_updata.Checked == false)
			{
				//tbxRecvData.AppendText("\r\n请选择升级模式\r\n");
				MessageBox.Show("请选择升级模式");
				return;
			}
			if((rdBtn_STM32.Checked == false)&&(rdBtn_ST87.Checked == false))
			{
				MessageBox.Show("请选择升级模块");
				return;
			}


			if(binSize%512 == 0)
			{
				progressBar1.Maximum = (int)binSize/512;
			}
			else
			{
				progressBar1.Maximum = (int)(binSize/512+1);
			}
			tbxRecvData.AppendText("共计 "+progressBar1.Maximum+" 帧\r\n");

			progressBar1.Minimum = 0;
			progressBar1.Visible = true;

            UInt16 MsgLen = 10;
            UInt16 FunID = 1;
            byte[] tmpbyte = new byte[1200];
            sendBuffer = new byte[1200 * 2];


            tmpbyte[0] = 0x5F;
            tmpbyte[1] = 0x5F;
            tmpbyte[2] = (byte)(MsgLen&0xFF);
            tmpbyte[3] = (byte)((MsgLen>>8)&0xFF);
            tmpbyte[4] = (byte)(FunID&0xFF);
            tmpbyte[5] = (byte)((FunID>>8)&0xFF);
            tmpbyte[6] = (byte)(binSize&0xFF);
            tmpbyte[7] = (byte)((binSize>>8)&0xFF);
            tmpbyte[8] = (byte)((binSize>>16)&0xFF);
            tmpbyte[9] = (byte)((binSize>>24)&0xFF);
            tmpbyte[10] = (byte)((binCheckSum16)&0xFF);
            tmpbyte[11] = (byte)((binCheckSum16>>8)&0xFF);
            tmpbyte[12] = 0;
            tmpbyte[13] = 0;
            tmpbyte[14] = 0x55;
            tmpbyte[15] = 0xAA;
            UInt16 MsgCheckSum16 = CheckSum16(tmpbyte,4,8);
            tmpbyte[12] = (byte)(MsgCheckSum16&0xFF);
            tmpbyte[13] = (byte)((MsgCheckSum16>>8)&0xFF);

            Byte2Ascii(sendBuffer,tmpbyte,16);

            if(sp.IsOpen)
            {
            	if(rdBtn_STM32.Checked == true)
            	{
	            	sendSerailPortData("IIAP_STM32");
	            	sp.Write(sendBuffer, 0, (int)((6+MsgLen)*2));
	            	sendSerailPortData("\r\n");
            	}
            	else
            	{
            		sendSerailPortData("IIAP_ST87");
	            	sp.Write(sendBuffer, 0, (int)((6+MsgLen)*2));
	            	sendSerailPortData("\r\n");
            	}
            }
		}

		void Byte2Ascii(byte[] des,byte[] src,UInt16 cnt)
		{
		    byte high;
		    byte low;
		    UInt16 i = cnt;
		    for(i=0;i<cnt;i++)
		    {
		    	high = (byte)(src[i] >> 4);
		    	low  = (byte)(src[i] & 0xf);
			    if (high > 9)
			    	high = (byte)(high + 'A' - 0xA);
			    else
			    	high = (byte)(high + '0');
			    des[i*2] = high;

			    if (low > 9)
			    	low = (byte)(low + 'A' - 0xA);
			    else
			    	low = (byte)(low + '0');
			    des[i*2+1] = low;
		    }
		}

		void Ascii2Byte(byte[] des,byte[] src,UInt16 cnt)
		{
			UInt32 i = 0;
			UInt32 j = 0;
			byte highData;
			byte lowData;
			while (i < cnt)
			{
				if (src[i] <= '9' && src[i] >= '0')
					highData = (byte)(src[i] - '0');
				else
					highData = (byte)(src[i] - 'A' + 0xa);
				i++;
				if (src[i] <= '9' && src[i] >= '0')
					lowData = (byte)(src[i] - '0');
				else
					lowData = (byte)(src[i] - 'A' + 0xa);
				des[j] = (byte)(lowData + (highData << 4));
				j++;
				i++;
			}
		}
		void BtnStopSendFileClick(object sender, EventArgs e)
		{
			sFlgSendOver = true;
			tbxRecvData.Clear();
			progressBar1.Visible = false;
		}

		void Btn_clearClick(object sender, EventArgs e)
		{
			tbxRecvData.Clear();
		}
		void BtnSendData_1Click(object sender, EventArgs e)
		{
			sendMultiSerialPortData(tbxSendData_1.Text);
		}
		void BtnSendData_2Click(object sender, EventArgs e)
		{
			sendMultiSerialPortData(tbxSendData_2.Text);
		}
		void BtnSendData_3Click(object sender, EventArgs e)
		{
			sendMultiSerialPortData(tbxSendData_3.Text);
		}
		void BtnSendData_4Click(object sender, EventArgs e)
		{
			sendMultiSerialPortData(tbxSendData_4.Text);
		}
		void BtnSendData_5Click(object sender, EventArgs e)
		{
			sendMultiSerialPortData(tbxSendData_5.Text);
		}
		void BtnSendData_6Click(object sender, EventArgs e)
		{
			sendMultiSerialPortData(tbxSendData_6.Text);
		}
		void BtnSendData_7Click(object sender, EventArgs e)
		{
			sendMultiSerialPortData(tbxSendData_7.Text);
		}
		void BtnSendData_8Click(object sender, EventArgs e)
		{
			sendMultiSerialPortData(tbxSendData_8.Text);
		}
		void BtnSendData_9Click(object sender, EventArgs e)
		{
			sendMultiSerialPortData(tbxSendData_9.Text);
		}
		void BtnSendData_10Click(object sender, EventArgs e)
		{
			sendMultiSerialPortData(tbxSendData_10.Text);
		}
		void Btn_clearSettingClick(object sender, EventArgs e)
		{

			sendMultiSerialPortData("AT+Write=1,homer 1500000000");
			System.Threading.Thread.Sleep(10);
			sendMultiSerialPortData("AT+Read=1");
		}
		void RdBtn_STM32CheckedChanged(object sender, EventArgs e)
		{
			//
		}
		void RdBtn_ST87CheckedChanged(object sender, EventArgs e)
		{
			//
		}
		void RdBtn_STM32Click(object sender, EventArgs e)
		{
			MessageBox.Show("确认是否为 STM32 升级？");
		}
		void RdBtn_ST87Click(object sender, EventArgs e)
		{
			MessageBox.Show("确认是否为 ST87 升级？");
		}


	}
}
